import webbrowser

from flask import Flask, render_template, jsonify
from flask import request
from flask_cors import CORS

from modules.storage.file_store import FileStore
from scrapy_main.config.aws_service import AwsService
from scrapy_main.config.main import ConfigMain
from scrapy_main.schedule.main import ScheduleMain
from utils.format import convert_dict_keys
from utils.hashsecret import verify_pass
from utils.os_main import get_files_list, get_abs_file_path, does_file_exist

# 引入flask实例
flask_app = Flask(__name__, static_folder='dist/static', template_folder='dist')


@flask_app.route('/beginScrapy', methods=['POST'])
def begin_scrapy():
    params = convert_dict_keys(request.json)
    # params['database_config_param'] = convert_dict_keys(params['database_config_param'])
    # 获取后再写入文件中
    script_name = params['script_name']

    scheduler = ScheduleMain(script_name)
    return_msg = scheduler.run(params)
    return jsonify(return_msg)

@flask_app.route('/saveScraperScript', methods=['POST'])
def save_scraper_script():
    params = convert_dict_keys(request.json)
    # 获取后再写入文件中
    script_name = params['script_name']

    script_location = get_abs_file_path(f"scrapy_main/scripts/{script_name}.json")
    file = FileStore(script_location, write_file_mode='w')
    params.pop('database_config_param', None)
    file.write(params)

    return jsonify({
        'code': 200,
        'msg': '保存成功'
    })


@flask_app.route('/endScrapy', methods=['POST'])
def end_scrapy():
    return jsonify({
        'code': 200,
        'msg': '成功终止'
    })


# 使用这个修饰器声明路由
@flask_app.route('/')
# 视图函数
def index():
    # 返回模板
    return render_template('index.html')



@flask_app.route('/getScrapersList', methods=['GET'])
def get_scrapers_list():
    scrapers_list = get_files_list('scrapy_main/scripts')
    new_scrapers = [scraper.split('.')[0] for scraper in scrapers_list]
    return jsonify({
        'data': new_scrapers,
        'code': 200})


@flask_app.route('/getScraperScriptByName', methods=['GET'])
def get_scraper_config_by_name():
    script_name = request.args.get('scriptName')
    script_location = get_abs_file_path(f"scrapy_main/scripts/{script_name}.json")
    file = FileStore(script_location)
    result_data = {}
    if does_file_exist(script_location):
        result_data = file.read()
    # 如果没有相应的脚本就返回空对象
    return jsonify({
        'data': result_data,
        'code': 200}
    )


# 获取配置信息
@flask_app.route('/getConfigs', methods=['GET'])
def get_configs():
    try:
        config = ConfigMain()
        data = config.get_config()
        response = {
            'data': data,
            'code': 200
        }
    except Exception as e:
        # 捕获所有异常，避免程序崩溃
        response = {
            'msg': str(e),
            'code': 500
        }

    return jsonify(response)


# 获取配置信息
@flask_app.route('/getConfigByKey', methods=['GET'])
def get_config_by_key():
    try:
        # 获取请求参数
        database_config_name = request.args.get('databaseConfigName')

        # 验证参数是否存在
        if not database_config_name:
            raise ValueError("Missing 'databaseConfigName' parameter")

        # 创建 ConfigMain 实例
        config = ConfigMain()

        # 获取配置值
        config_value = config.get_config_value_by_key(database_config_name)

        # 构建响应
        response = {
            'data': config_value,
            'code': 200
        }
    except ValueError as ve:
        # 处理缺少参数的情况
        response = {
            'msg': str(ve),
            'code': 400
        }
    except Exception as e:
        # 处理其他异常
        response = {
            'msg': str(e),
            'code': 500
        }

    return jsonify(response)

# 检查密码
@flask_app.route('/checkConnectPassword', methods=['POST'])
def check_connect_password():
    """

    Request JSON format:
    {
        'type': '',  # 类型
        'value': ''  # 值
    }

    Response JSON format:
    {
        'data': '',  # 返回的数据
        'code': ''  # 状态码
        'msg': ''  # 错误信息
    }
    """
    # 检查密码
    params = convert_dict_keys(request.json)
    aws_dict = AwsService(bucket_name='joescrapy').get_json_from_file('connection_pass.json') or {}
    response_data = {'data': '', 'code': 0}

    if not aws_dict:
        response_data.update({'msg': '文件出错', 'code': 500})
    else:
        saved_value = aws_dict.get(params.get('type'))
        response_data.update({'data': 'ok', 'code': 200}) if saved_value and verify_pass(params.get('value'),
                                                                                         saved_value.get(
                                                                                             'password')) else \
            response_data.update({'msg': '身份信息错误', 'code': 500})

    return jsonify(response_data)


# 测试用
def open_browser():
    # 在此处指定你的 Flask 服务地址和端口号
    url = "http://127.0.0.1:5000/"
    webbrowser.open_new(url)


def flask_run_web(debug=True):

    # 启动服务
    if debug:
        # open_browser()
        CORS(flask_app)  # 启用 CORS，允许所有域名访问
        # 把debug参数设为True启动调试模式
        flask_app.run(debug=True)
    else:
        flask_app.run(host='0.0.0.0', port=5100)
